package cn.ainit.sys.framework.save;

import java.io.Reader;
import java.io.StringReader;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import oracle.jdbc.OracleConnection;
import oracle.jdbc.OraclePreparedStatement;
import oracle.sql.CLOB;

import org.hibernate.Query;
import org.hibernate.dialect.function.VarArgsSQLFunction;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.sun.org.apache.bcel.internal.generic.Select;


import cn.ainit.common.ReturnObject;
import cn.ainit.sys.common.dao.SysBaseDao;
import cn.ainit.sys.ds.cloumns.sysCloumns;
import cn.ainit.sys.framework.entity.SysColumns;
import cn.ainit.sys.framework.upload.UploadDao;
import cn.ainit.sys.menu.SessionCont;
import cn.ainit.sys.query.datastore.DataStore;
import cn.ainit.sys.utils.MD5Util;
import cn.ainit.sys.utils.UUID32;

@Transactional
@Repository
public class CommonSaveDaoImpl extends SysBaseDao implements CommonSaveDao {
	@Override
	public boolean testSave(String sql) throws Exception {
		this.getJdbcTemplate().execute(sql);
		return true;
	}


	private UploadDao uploadDao;
	@Resource
	public void setUploadDao(UploadDao uploadDao) {
		this.uploadDao = uploadDao;
	}



	@Override
	public boolean saveObj(String sql, List<String> values)
	throws Exception {
		Connection conn = this.getJdbcTemplate().getDataSource().getConnection();
		PreparedStatement statement = conn.prepareStatement(sql);

		try {
			for (int i = 0; i < values.size(); i++) {
				if (values.get(i).indexOf("-") >= 0) {
					//System.out.println("values.get(i):"+values.get(i));
					//System.out.println("values.get(i).split(-)[0]:"+values.get(i).split("-")[0]);
					if(values.get(i).split("-")[0]!=null&&!values.get(i).split("-")[0].trim().equals("")){   //当表示时间的列为空时,要进行飞空判断否则报错
						statement.setTimestamp(i+1,new Timestamp(Long.parseLong(values.get(i).split("-")[0])));
					}else{
						statement.setTimestamp(i+1, null);
					}
				}else {
					statement.setString(i+1, values.get(i));
				}
			}
			statement.execute();
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}finally{
			if (statement != null) {
				statement.close();
			}
			if (conn != null) {
				conn.close();
			}
		}
		return true;
	}
	@Override
	public List<SysColumns> loadColumns(String dsId) throws Exception {
		return this.getSessionFactory().getCurrentSession().createQuery("from SysColumns s  where s.dsid = ?")
		.setString(0, dsId).list();
	}

	@Override
	public DataStore loadDS(String dsId) throws Exception {
		List<DataStore> dataStores = this.getSessionFactory().getCurrentSession().createQuery("from DataStore s where s.dsId = ?")
		.setString(0, dsId).list();
		if (dataStores != null || (dataStores.size()>0)) {
			return dataStores.get(0);
		}else {
			throw new RuntimeException("未找到DS");
		}
	}

	@Override
	public boolean updateObj(String sql, List<String> cValues,
			List<String> wValues) throws Exception {
		Connection conn = this.getJdbcTemplate().getDataSource().getConnection();
		PreparedStatement statement = conn.prepareStatement(sql);
		try {
			int tmp = cValues.size() + 1;
			for (int i = 0; i < cValues.size(); i++) {
				if (cValues.get(i).indexOf("-") >= 0) {
					statement.setTimestamp(i+1,new Timestamp(Long.parseLong(cValues.get(i).split("-")[0])));
				}else {
					statement.setString(i+1, cValues.get(i));
				}
			}
			for (int i = 0; i < wValues.size(); i++) {
				if (wValues.get(i).indexOf("-") >= 0) {
					statement.setTimestamp(tmp+i,new Timestamp(Long.parseLong(wValues.get(i).split("-")[0])));
				}else {
					statement.setString(tmp+i, wValues.get(i));
				}
			}
			statement.execute();

		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}finally{
			if (statement != null) {
				statement.close();
			}
			if (conn != null) {
				conn.close();
			}
		}
		return true;
	}

	/** 
	 * 保存一条记录. 
	 * 如果该记录存在，则更新之，如果该记录不存在，则插入。
	 * 如果第一个主键的值为null||""，则自动插入新的主键值，这个方法不适合对含多主键的表进行插入操作，但不影响对多主键的表进行更新 
	 * 
	 * @param tableName 是表名 
	 * @param mapRecord 是准备插入到表中的一条记录的数据,其键名与字段名相同,顺序无关; 
	 * @return 返回标准update方法返回的状态值 
	 * @throws SQLException 
	 */
	@Override  
	public ReturnObject saveComm(String diu,String dsid,Map<String, Object> mapRecord,HttpSession session) throws Exception {  
		ReturnObject returnObject = new ReturnObject();
		StatementParamT sparam = new StatementParamT();
		DataStore dataStore = new DataStore();
		dataStore = loadDS(dsid);
		if (dataStore == null) {
			throw new RuntimeException("DSID传入错误,找不到DSID=["+dsid+"]的记录");
		}
		String tableName = dataStore.getUpdateTable();

		//查找数据库的配置 ，是否只有一个主键不能采用联合主键   主要用户执行存储过程的时候需要用到的后置存储过程
		String tablePk = "select a.constraint_name,  a.column_name from user_cons_columns a, user_constraints b "+
		" where a.constraint_name = b.constraint_name "+
		" and b.constraint_type = 'P' and a.table_name = '"+tableName.toUpperCase()+"'";

		List<Map<String, Object>> loadTablePk =  this.getJdbcTemplate().queryForList(tablePk);
		if (loadTablePk == null || loadTablePk.size()!=1) {
			throw new RuntimeException("表["+tableName.toUpperCase()+"],没有设置唯一的主键列,不能进行修改" +
					",DSID=["+dsid+"]");
		}
		String tablePkName = loadTablePk.get(0).get("COLUMN_NAME").toString();		

		int num = 0;  
		StringBuffer _w = new StringBuffer("");
		List<SysColumns> keyColns = new ArrayList<SysColumns>();//主键
		List<SysColumns> columns = getClns(dsid);
		//将数据库中的字段缓存为Map
		Map<String, SysColumns> colsMap = new HashMap<String, SysColumns>();  // 所有的字段信息   Map<NAME,SysColumns>
		for (int i = 0; i < columns.size(); i++) {
			colsMap.put(columns.get(i).getName(), columns.get(i));
			if (("T").equals(columns.get(i).getIsPkAdd())) {
				keyColns.add(columns.get(i));
			}
		}

		String[] keys = new String[keyColns.size()];
		Connection conn = this.getJdbcTemplate().getDataSource().getConnection();
		PreparedStatement stmt = null;
		Map<String, String> clnTypeMap = new HashMap<String, String>();
		clnTypeMap = loadAllClnProperty(tableName);		//获取所有的字段类型

		//将所有不是本表的字段移除
		Object[] jmMap = mapRecord.keySet().toArray();
		for (int i = 0; i < jmMap.length; i++) {
			System.out.println("CommonSaveDaoImpl #L.182#"+jmMap[i].toString());
			System.out.println(colsMap.containsKey(jmMap[i].toString())+":"+!colsMap.containsKey(jmMap[i].toString()));
			if (!clnTypeMap.containsKey(jmMap[i].toString())) {
				mapRecord.remove(jmMap[i].toString());
			}
		}
		try {
			for (int i = 0; i < keyColns.size(); i++) {
				keys[i] = keyColns.get(i).getName();	//获取表的所有主键字段名
			}
			if (keys.length == 0) {  
				throw new RuntimeException("没有配置主键字段，请配置SysColumns中,DSID=["+dsid+"]主键字段");//无主键的表提示设置主键
			}
			if("0".equals(diu)){//添加
				if (checkPkValue(keys,mapRecord,diu)) { //检测主键是否有空值
					//获取到主键，设置主键
					returnObject = insertN(dsid,diu,clnTypeMap,colsMap,keys,tableName, mapRecord, true,session,tablePkName);//表有主键，但记录中不含主键记录||主键记录值是null||主键值是""，则插入，并自动插入主键  

				}
			}else if("1".equals(diu)){//更新
				//有主键
				if (!checkPkValue(keys,mapRecord,diu)) { //检测主键是否有空值
					throw new RuntimeException("更新失败，DSID=["+dsid+"]字段更新主键没有传入，请检查！");//无主键的表提示设置主键
					//获取到主键，设置主键
					//		        	returnObject = insertN(diu,clnTypeMap,colsMap,keys,tableName, mapRecord, true);//表有主键，但记录中不含主键记录||主键记录值是null||主键值是""，则插入，并自动插入主键  
				} else {
					//有主键值
					Object[] recordFields = mapRecord.keySet().toArray();  //将前台所有字段提取
					Map _key_m = new LinkedHashMap();
					Map _other_m = new HashMap();
					for (int i = 0; i < recordFields.length; i++) {  
						if (isInFields(keys, recordFields[i].toString())) { //记录中是否有主键  
							//将记录中的主键移到key_m中；保证不对主键更新  
							_key_m.put(recordFields[i].toString(), mapRecord.get(recordFields[i].toString()));
						}else {
							_other_m.put(recordFields[i].toString(), mapRecord.get(recordFields[i].toString()));
						}
					}

					if (!_key_m.isEmpty()) {  
						Object[] _k = _key_m.keySet().toArray();  //得到所有的有效字段
						if (_k.length != keys.length) {  //判断字段和主键是否一样
							throw new RuntimeException("<font color:'#E08523'>【请反馈开发】约束主键传入个数和数据库表不一致,请检查</font>");
							//		                	returnObject.setMsg("fail");
							//		                	returnObject.setInfo("主键传入个数和表不一致");
							//		                    return returnObject;  
						} else {
							String typeClassName = "";
							_w.append(" where  ");
							StringBuffer tmpQueryOne = new StringBuffer();
							for (int i = 0; i < _k.length; i++) {
								typeClassName = getField(tableName, _k[i].toString(),clnTypeMap);//获取主键字段对象
								if (i > 0) {
									_w.append(" and ");  
								}
								if (typeClassName.equals("VARCHAR2")) {  
									_w.append(_k[i] + " = '" + mapRecord.get(_k[i].toString()) + "'");  
								} else {  
									_w.append(_k[i] + " = '" + mapRecord.get(_k[i].toString()) + "'");  
								}

							}
							Map rm = this.queryOne("select "+_k[0]+" from " + tableName + _w);  
							if (rm.isEmpty()) {  
								throw new RuntimeException("【请反馈开发】在数据库中找不到该数据,因此无法更新<br/><font color:'#E08523'>[可能原因:主键传入有误，系统中找不到该数据]</font>");
								//		                    	returnObject.setMsg("fail");
								//		                    	returnObject.setInfo("主键传入有误，系统中找不到该数据");
							} else {  
								returnObject = this.update(diu,clnTypeMap,colsMap,tableName, _other_m, _w.toString());//原原本本地更新  
							}  
						}  
					}else{
						System.out.println("主键没获取到");
					}
				} 
			}else if("2".equals(diu)){//删除
				//有主键
				if (!checkPkValue(keys,mapRecord,diu)) { //检测主键是否有空值
					//获取到主键，设置主键
					throw new RuntimeException("删除失败，DSID=["+dsid+"]字段更新主键没有传入，请检查！");//无主键的表提示设置主键
				} else {
					//有主键值
					Object[] recordFields = mapRecord.keySet().toArray();  //将前台所有字段提取
					Map _key_m = new LinkedHashMap();
					Map _other_m = new HashMap();
					for (int i = 0; i < recordFields.length; i++) {  
						if (isInFields(keys, recordFields[i].toString())) { //记录中是否有主键  
							//将记录中的主键移到key_m中；保证不对主键更新  
							_key_m.put(recordFields[i].toString(), mapRecord.get(recordFields[i].toString()));
						}else {
							_other_m.put(recordFields[i].toString(), mapRecord.get(recordFields[i].toString()));
						}
					}

					if (!_key_m.isEmpty()) {  
						Object[] _k = _key_m.keySet().toArray();  //得到所有的有效字段
						if (_k.length != keys.length) {  //判断字段和主键是否一样
							throw new RuntimeException("<font color:'#E08523'>【请反馈开发】约束主键传入个数和数据库表不一致,请检查</font>");
							//		                	returnObject.setMsg("fail");
							//		                	returnObject.setInfo("主键传入个数和表不一致");
							//		                    return returnObject;  
						} else {
							String typeClassName = "";
							_w.append(" where  ");
							StringBuffer tmpQueryOne = new StringBuffer();
							for (int i = 0; i < _k.length; i++) {
								typeClassName = getField(tableName, _k[i].toString(),clnTypeMap);//获取主键字段对象
								if (i > 0) {
									_w.append(" and ");  
								}
								if (typeClassName.equals("VARCHAR2")) {  
									_w.append(_k[i] + " like '" + mapRecord.get(_k[i].toString()) + "'");  
								} else {  
									_w.append(_k[i] + " = " + mapRecord.get(_k[i].toString()));  
								}

							}
							Map rm = this.queryOne("select "+_k[0]+" from " + tableName + _w);  
							if (rm.isEmpty() && rm.size() != 1) {  
								throw new RuntimeException("在数据库中找不到该数据,因此无法删除<br/><font color:'#E08523'>[可能原因:已经被其他用户删除，系统中找不到该数据]</font>");
								//		                    	returnObject.setMsg("fail");
								//		                    	returnObject.setInfo("在数据库中找不到该数据无法更新<br/>[可能原因:主键传入有误，系统中找不到该数据]");
								//		                    	returnObject = this.insert(diu,colsMap,tableName, mapRecord,conn,stmt);//原原本本地插入  
							} else {  
								returnObject = this.deleteN(diu,clnTypeMap,colsMap,tableName, _other_m, _w.toString());//删除数据
							}  
						}  
					}  
				} 
			}else {
				throw new RuntimeException("操作状态更新错误,找不到diu,请联系开发解决");
			}
			conn.commit();
		}catch (Exception e) {
			e.printStackTrace();
			throw e;
		}finally{
			if (stmt != null) {
				stmt.close();
			}
			if (conn != null) {
				conn.close();
			}
		}
		return returnObject;  
	}

	/***
	 * 删除数据
	 * @param diu
	 * @param clnTypeMap
	 * @param colsMap
	 * @param tableName
	 * @param _other_m
	 * @param whereStr
	 * @return
	 * @author Xuzq
	 * @date 2014-4-28 下午02:27:10
	 */
	public ReturnObject deleteN(String diu,Map clnTypeMap,Map colsMap,String tableName, Map<String, Object> _other_m, String whereStr) throws Exception{
		System.out.println("Delete Record Ing....");
		Connection conn=null;
		PreparedStatement stmt=null;
		ReturnObject returnObject = new ReturnObject();
		try {
			conn = this.getJdbcTemplate().getDataSource().getConnection();
			StatementParamT paramT = new StatementParamT();
			paramT.getSql().append(" delete from  "+ tableName +" ");
			paramT.getSql().append(whereStr);
			stmt = conn.prepareStatement(paramT.getSql().toString());
			System.out.println("删除数据："+paramT.getSql().toString());
			System.out.println("参数：");
			returnObject.setTraState(stmt.executeUpdate());
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}finally{
			if (stmt != null) {
				stmt.close();
			}
			if (conn != null) {
				conn.close();
			}
		}
		return returnObject;
	}

	/**
	 * 
	 * @param dsid
	 * @param diu
	 * @param clnTypeMap
	 * @param colsMap
	 * @param tableName
	 * @param mapRecord
	 * @param session
	 * @param tablePkName 真正表的主键
	 * @return
	 * @throws Exception
	 * @author Xuzq
	 * @date 2014-5-28 下午04:38:33
	 */
	//无主键的表可以直接插入             标志位	    	字段类型	     所有的字段信息     					表名				前台传入的记录					session  
	public  ReturnObject insert(String dsid,String diu,Map clnTypeMap,Map<String,SysColumns> colsMap,String tableName, 
			Map<String, Object> mapRecord,HttpSession session,String tablePkName) throws Exception{
		Connection conn=null;
		PreparedStatement stmt = null;
		System.out.println("拼接值，直接插入");
		ReturnObject returnObject = new ReturnObject();
		StatementParamT pam = new StatementParamT();
		//默认值在数据库中设置，或者后期优化修改这里
		pam.getSql().append("insert into "+tableName+" (");
		pam.getTmpSql().append(" values (");
		Object[] clns = mapRecord.keySet().toArray();
		List clns_bak = new ArrayList();

		Object tmpCv = null;
		Object typeName = null;

		int tmpFlag = 0;

		for (int i = 0; i < clns.length; i++) {
			typeName = clnTypeMap.get(clns[i]);
			if (typeName == null) {
				System.out.println("在数据表中找不到字段["+clns[i].toString()+"],请检查表 ["
						+tableName+"]是否有该字段");
				//				throw new RuntimeException("在数据表中找不到字段["+clns[i].toString()+"],请检查表 ["
				//						+tableName+"]是否有该字段");
				continue;
			}
			pam.getSql().append(clns[i].toString());
			pam.getTmpSql().append("?");
			tmpCv = mapRecord.get(clns[i].toString());
			clns_bak.add(clns[i]);
			//传入的值处理成默认值
			pam.getCvalues().add(getClnValues(dsid,clns[i].toString(),tmpCv,colsMap.get(clns[i].toString()),clnTypeMap,session,false,mapRecord));
			pam.getSql().append(",");
			pam.getTmpSql().append(",");
		}
		//获取需要填写默认值的字段而前台没传入
		Object[] needCln = getNeedValueCln(colsMap,clns);
		for (int i = 0; i < needCln.length; i++) {
			pam.getSql().append(needCln[i].toString());
			pam.getTmpSql().append("?");
			typeName = clnTypeMap.get(needCln[i]);
			if (typeName == null) {
				throw new RuntimeException("在数据表中找不到字段["+needCln[i].toString()+"],请检查表 ["
						+tableName+"]是否有该字段");
			}
			//传入的值处理成默认值
			pam.getCvalues().add(getClnValues(dsid,needCln[i].toString(),"",colsMap.get(needCln[i].toString()),clnTypeMap,session,true,mapRecord));
			pam.getSql().append(",");
			pam.getTmpSql().append(",");
		}
		//处理逗号
		pam.setSql(new StringBuffer(pam.getSql().substring(0, pam.getSql().length()-1).toString()));
		pam.setTmpSql(new StringBuffer(pam.getTmpSql().substring(0, pam.getTmpSql().length()-1).toString()));

		pam.getSql().append(")" + pam.getTmpSql().toString() + ")");
		try {
			conn = this.getJdbcTemplate().getDataSource().getConnection();
			stmt = conn.prepareStatement(pam.getSql().toString());
			System.out.println(pam.getSql().toString());
			for (int i = 0; i < clns_bak.size(); i++) {
				if (pam.getCvalues().get(i).indexOf("-DATE") > 0) {
					//如果有时间字段，则设置为时间
					stmt.setTimestamp(i+1, new Timestamp(Long.parseLong(pam.getCvalues().get(i).split("\\-")[0])));
					System.out.println(i+1+":"+pam.getCvalues().get(i));
				}else {
					stmt.setString(i+1, pam.getCvalues().get(i));
					System.out.println(i+1+":"+pam.getCvalues().get(i));
				}
			}
			for (int i = 0; i < needCln.length; i++) {
				if (pam.getCvalues().get(i+clns_bak.size()).indexOf("-DATE") > 0) {
					//如果有时间字段，则设置为时间
					stmt.setTimestamp(i+1+clns_bak.size(), new Timestamp(Long.parseLong(pam.getCvalues().get(i+clns_bak.size()).split("\\-")[0])));
					System.out.println(i+1+clns_bak.size()+":"+pam.getCvalues().get(i+clns_bak.size()));
				}else {
					stmt.setString(i+1+clns_bak.size(), pam.getCvalues().get(i+clns_bak.size()));
					System.out.println(i+1+clns_bak.size()+":"+pam.getCvalues().get(i+clns_bak.size()));
				}
			}
			returnObject.setTraState(stmt.executeUpdate());
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}finally{
			if (stmt != null) {
				stmt.close();
			}
			if (conn != null) {
				conn.close();
			}
		}
		return returnObject;
	} 

	/**
	 * 获取所有需要填写的字段
	 * @param colsMap 所有字段
	 * @param clns	原有字段
	 * @return
	 * @author Xuzq
	 * @date 2014-4-28 下午04:24:55
	 */
	private Object[] getNeedValueCln(Map<String,SysColumns>  colsMap,Object[] clns){
		Map<String, String> clnsMap = new HashMap<String, String>();
		for (int i = 0; i < clns.length; i++) {
			clnsMap.put(clns[i].toString(), clns[i].toString());
		}
		List<String> nameList = new ArrayList<String>();
		Object[] allClns  = colsMap.keySet().toArray();
		SysColumns sysColumns = null;
		for (int i = 0; i < allClns.length; i++) {
			sysColumns = colsMap.get(allClns[i].toString());
			if (sysColumns.getDefaultValueAdd() != null && !("".equals(sysColumns.getDefaultValueAdd()))
					&& !clnsMap.containsKey(sysColumns.getName())) {
				nameList.add(sysColumns.getName());
			}
		}
		return nameList.toArray();
	}

	/**
	 *  设置默认值规则
	 *  defaultValue   $uid   $name $uid   $depid   $staid
	 *  			   C- xx   常量
	 *  			   F- xx   ORACLE方法  IN_VALUE 
	 *  			   P- xx   ORACLE存储过程  IN_VALUE  OUT_VALUE
	 *  			   D- xxx	定制编号  F001
	 * @param oldValues	原值
	 * @param clnName 字段名
	 * @param column 字段的参数
	 * @param clnTypeMap 所有字段数据库中的类型
	 * @param flag     false 为前台传入 true 为系统默认
	 * @return
	 * @author Xuzq
	 * @date 2014-4-28 下午03:24:26
	 */
	//																																			传入的参数
	public String getClnValues(String dsid,String clnName,Object oldValues,SysColumns column,Map clnTypeMap,HttpSession session,boolean flag,Map<String, Object> mapRecord) throws Exception{
		String newValue = "";
		Object typeName = clnTypeMap.get(clnName);
		Object tmp = null;
		if (("DATE").equals(typeName.toString())) {
			newValue = (oldValues!=null && !"".equals(oldValues.toString())) ? oldValues+"-DATE":"0-DATE";
		}else {
			String defaultValue = column.getDefaultValueAdd();
			if (defaultValue !=null && defaultValue.indexOf("$") == 0) {
				if ("date".equals(defaultValue.substring(1, defaultValue.toString().length())) ) {
					newValue = System.currentTimeMillis()/1000*1000+"-DATE";
				}else {
					tmp =  session.getAttribute(defaultValue.substring(1,defaultValue.length()));
					newValue = tmp == null?"":tmp.toString();
				}
			}else if (defaultValue !=null && defaultValue.indexOf("D")  == 0) {
				//定制方法
				if (defaultValue.substring(2,defaultValue.length()).equalsIgnoreCase("F001")) {
					System.out.println(dsid+"==========编码优化中   L.543");

					//					if(mapRecord.get("STATION_ID") == null) throw new RuntimeException("请选择站点信息");
					//					String stationId = mapRecord.get("STATION_ID").toString();
					Object stationId = session.getAttribute(SessionCont.STATION_ID);
					if (stationId == null) {
						throw new RuntimeException("没有登录,请重新登录");
					}
					newValue = getCodeStr(dsid,stationId.toString(),"1");
				}
			}else if (defaultValue !=null && defaultValue.indexOf("C")  == 0) {
				//常量
				newValue = defaultValue.substring(2,defaultValue.length());
			}else{
				newValue = oldValues==null?"":oldValues.toString();
			}
		}
		System.out.println("新旧值转换.........");
		return newValue;
	}

	/**
	 * 
	 * @param keys  本表的主键字段
	 * @param mapRecord  前台传入的参数
	 * @param diu
	 * @return
	 * @author Xuzq
	 * @date 2014-4-26 下午03:50:10
	 */
	public boolean checkPkValue(String[] keys,Map<String, Object> mapRecord,String diu){
		Object tmpkv = "";
		for (int i = 0; i < keys.length; i++) {
			tmpkv =  mapRecord.get(keys[i]);
			if ( tmpkv == null || "".equals(tmpkv.toString())) {
				if (("0").equals(diu)) { //添加

				}else {
					throw new RuntimeException("更新数据，主键"+keys[i]+"没有传入,请检查");
				}
			}else {
				if (("0").equals(diu)) {
					throw new RuntimeException("目前主键都不需要输入值，请不要输入字段["+ keys[i] +"]");
				}
			}
		}
		return true;
	}

	//直接拼接执行sql语句
	public int executeObj(String tableName, Map<String, Object> mapRecord) throws Exception{
		//insert into BJ_XT (XT_ID,XT_CODE,XT_NAME) VALUES ('XXXX2','AAAAA','选题20140414')
		StringBuffer sql = new StringBuffer("insert into "+tableName+" (");

		Object[] fields =  mapRecord.keySet().toArray();

		Connection conn = null;
		Statement stmt = null;
		int num = 0;
		try {
			conn = this.getJdbcTemplate().getDataSource().getConnection();
			stmt = conn.prepareStatement(sql.toString());
			num = stmt.executeUpdate(sql.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if (stmt != null) {
				stmt.close();
			}
			if (conn != null) {
				conn.close();
			}
		}
		return num;
	}

	/***
	 * 
	 * @param dsid
	 * @param diu
	 * @param clnTypeMap
	 * @param colsMap
	 * @param keys
	 * @param tableName
	 * @param mapRecord
	 * @param flag
	 * @param session
	 * @param tablePkName 正式表的主键
	 * @return
	 * @throws Exception
	 * @author Xuzq
	 * @date 2014-5-28 下午04:22:13
	 */
	//表有主键，但记录中不含主键记录||主键记录值是null||主键值是""，则插入，并自动插入主键  
	//设置主键并返回
	public ReturnObject insertN(String dsid,String diu,Map clnTypeMap,Map colsMap,String[] keys,String tableName, 
			Map<String, Object> mapRecord, boolean flag,HttpSession session,String tablePkName) throws Exception{
		System.out.println("设置主键之后插入");
		Connection conn=null;
		PreparedStatement stmt=null;
		ReturnObject returnObject = new ReturnObject();
		try {
			conn = this.getJdbcTemplate().getDataSource().getConnection();
			//设置主键值
			//然后调用插入sql语句
			Object tmpkv = null;
			String tmpV = "";
			String pkVal = "";
			StringBuffer returnBuf = new StringBuffer();
			for (int i = 0; i < keys.length; i++) {
				tmpkv =  mapRecord.get(keys[i]);
				if ( tmpkv == null || "".equals(tmpkv.toString())) {
					tmpV = UUID32.newGuid();
					mapRecord.put(keys[i].toString(), tmpV);	//设置主键值
					returnBuf.append(keys[i]+"-"+tmpV);
				}
				if (tablePkName.equals(keys[i].toString())) {
					pkVal = tmpV.toString();
				}
			}
			returnObject = insert(dsid,diu,clnTypeMap,colsMap,tableName,mapRecord,session,tablePkName);
			returnObject.setInfob(returnBuf);
			returnObject.setPkValue(pkVal);
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}finally{
			if (stmt != null) {
				stmt.close();
			}
			if (conn != null) {
				conn.close();
			}
		}
		return returnObject;
	}

	//表有主键，但记录中不含主键记录||主键记录值是null||主键值是""，则插入，并自动插入主键  
	/**
	 * colsMap 所有的字段
	 * tableName 表名
	 * mapRecord 传入的记录
	 * whereStr 作whereStr
	 */
	public ReturnObject update(String diu,Map clnTypeMap,Map colsMap,String tableName, Map<String, Object> _other_m, String whereStr) throws Exception{
		System.out.println("Update Record Ing....");
		Connection conn=null;
		PreparedStatement stmt=null;
		ReturnObject returnObject = new ReturnObject();
		try {
			conn = this.getJdbcTemplate().getDataSource().getConnection();
			StatementParamT paramT = new StatementParamT();
			Object[] clns = _other_m.keySet().toArray();
			paramT.getSql().append(" update "+ tableName +" set ");
			String tmpClnName = "";
			for (int i = 0; i < clns.length; i++) {
				paramT.getSql().append(clns[i] +"=?");
				if (getField(tableName, clns[i].toString(),clnTypeMap).equals("DATE")) {
					paramT.getCvalues().add((_other_m.get(clns[i])==null?System.currentTimeMillis()+"-DATE":_other_m.get(clns[i]).toString())+"-DATE");
				}else{
					paramT.getCvalues().add(_other_m.get(clns[i])==null?"":_other_m.get(clns[i]).toString());
				}
				if (i < clns.length - 1) {
					paramT.getSql().append(",");
				}
			}
			paramT.getSql().append(whereStr);
			stmt = conn.prepareStatement(paramT.getSql().toString());
			System.out.println("更新数据："+paramT.getSql().toString());
			System.out.println("参数：");
			String[] tmpCValue = new String[2];
			for (int i = 0; i < paramT.getCvalues().size(); i++) {
				if (paramT.getCvalues().get(i).indexOf("-DATE") > 0) {
					tmpCValue = paramT.getCvalues().get(i).split("\\-");
					stmt.setTimestamp(i+1, new Timestamp(Long.parseLong(tmpCValue[0])));
				}else {
					stmt.setString(i+1, paramT.getCvalues().get(i));
				}
				System.out.print(paramT.getCvalues().get(i)+"|"); ////////////////////////////////////////
			}
			returnObject.setTraState(stmt.executeUpdate());
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}finally{
			if (stmt != null) {
				stmt.close();
			}
			if (conn != null) {
				conn.close();
			}
		}
		return returnObject;
	}

	//获取表主键
	public List<SysColumns> getKeys(String dsid){
		System.out.println("根据dsid获取表主键对象集合");
		List<SysColumns> keyColns = new ArrayList<SysColumns>();
		Query query = this.getSessionFactory().getCurrentSession().createQuery("from SysColumns sc where sc.dsid = ? and sc.isPkAdd = 'T'").setString(0, dsid);
		keyColns = query.list();
		return keyColns;
	}

	//判断是否有主键
	public boolean isInFields(String[] keys, String recordField){
		for (int i = 0; i < keys.length; i++) {
			if (keys[i].equals(recordField)) {
				return true;
			}
		}
		return false;
	}

	//获取字段的类型
	public String getField(String tableName, String fieldName,Map clnTypeMap) throws Exception{
		//一次性查询所有的字段类型
		Object tValue = null;
		tValue = clnTypeMap.get(fieldName);
		if (tValue == null || "".equals(tValue)) {
			throw new RuntimeException("在表["+tableName+"]中找不到["+fieldName+"]字段");
		}
		return tValue.toString();
	}

	public Map queryOne(String sql){
		Map map = new HashMap();
		map = this.getJdbcTemplate().queryForMap(sql);
		return map;
	}


	public void test2(){
		Map<String, Object> ms = new HashMap<String, Object>();
		ms.put("xx", "11");
		ms.put("B", "222");
		System.out.println(ms.get("dd"));
		System.out.println(ms.keySet().toString());

	}


	/*********
	 * 个性定制方法  获取流水号编码
	 * @param dsid
	 * @param stationId
	 * @param flag
	 * @return
	 * @throws Exception
	 * @author Xuzq
	 * @date 2014-6-21 上午11:21:28
	 */
	public String getCodeStr(String dsid,String stationId,String flag) throws Exception{
		String code = "";
		Connection conn=null;
		PreparedStatement stmt=null;
		try {
			//		pk_sys_code.up_getcode_custom(i_receipts_id => :i_receipts_id,
			//                i_station_id => :i_station_id,
			//                i_switch => :i_switch,
			//                o_code => :o_code);
			//pk_sys_code.up_getcode_custom(?,?,?,?);
			conn= this.getJdbcTemplate().getDataSource().getConnection();
			conn.setAutoCommit(false);
			String sql = "{Call pk_sys_code.up_getcode_custom(?,?,?,?)}";
			CallableStatement cs = conn.prepareCall(sql);
			cs = conn.prepareCall(sql);
			cs.setString(1,dsid);
			cs.setString(2,stationId);
			cs.setString(3, flag);
			cs.registerOutParameter(4,oracle.jdbc.OracleTypes.VARCHAR);
			cs.execute();
			code = cs.getString(4);
		}catch (Exception e) {
			e.printStackTrace();
			throw e;
		}finally{
			if (stmt != null) {
				stmt.close();
			}
			if (conn != null) {
				conn.close();
			}
		}
		return code;
	}
	/****
	 * 保存通用的一对多信息
	 */
	@Override
	public ReturnObject saveCommDG(String djdsid,String fkid,String diu,String sinId, String dsid, Map mapRecord,HttpSession session) throws Exception {
		ReturnObject returnObject = new ReturnObject();
		StatementParamT sparam = new StatementParamT();
		DataStore dataStore = new DataStore();
		dataStore = loadDS(dsid);
		if (dataStore == null) {
			throw new RuntimeException("DSID传入错误,找不到DSID=["+dsid+"]的记录");
		}
		String tableName = dataStore.getUpdateTable();
		String pkName = "";
		String fkName = "";
		Map<String, String> clnTypeMap = new HashMap<String, String>();
		clnTypeMap = loadAllClnProperty(tableName);		//获取所有的字段类型
		StringBuffer sql=new StringBuffer(); 
		List<SysColumns> columns = getClns(dsid); //所有的字段
		//将数据库中的字段缓存为Map
		Map<String, SysColumns> colsMap = new HashMap<String, SysColumns>();  // 所有的字段信息   Map<NAME,SysColumns>

		if(diu.equals("0")){   //添加
			sql = new StringBuffer("insert into "+tableName +"( ");
			Object tmp = null; //缓存字段名
			for (int i = 0; i < columns.size(); i++) {
				colsMap.put(columns.get(i).getName(), columns.get(i));
				sql.append(columns.get(i).getName());
				sparam.getTmpSql().append("?");
				if(i < columns.size()-1 ){
					sql.append(",");
					sparam.getTmpSql().append(",");
				}else{
					sql.append(") values (");
					sparam.getTmpSql().append(")");
				}
				tmp = mapRecord.get(columns.get(i).getName().toString());
				if ( "T".equals(columns.get(i).getPrimaryKey())){
					if( !"".equals(pkName))throw new RuntimeException("对照表"+tableName+"[dsid="+dsid+"]只允许有一个主键");
					pkName = columns.get(i).getName();
					sparam.getCvalues().add(UUID32.newGuid());
				}else if ("T".equals(columns.get(i).getIsFK())){
					if( !"".equals(fkName))throw new RuntimeException("对照表"+tableName+"[dsid="+dsid+"]只允许有一个外键");
					fkName = columns.get(i).getName();
					sparam.getCvalues().add(fkid);
				}else{
					if("DS_ID".equalsIgnoreCase(columns.get(i).getName())){
						sparam.getCvalues().add(djdsid);
					}else{
						sparam.getCvalues().add(tmp == null?"":tmp.toString());
					}
				}
			}
		}else{    //保存
			//先检查sinId是否为空
			//1.为空的时候是添加
			if(sinId==null||sinId.equals("")){
				sql = new StringBuffer("insert into "+tableName +"( ");
				Object tmp = null; //缓存字段名
				for (int i = 0; i < columns.size(); i++) {
					colsMap.put(columns.get(i).getName(), columns.get(i));
					sql.append(columns.get(i).getName());
					sparam.getTmpSql().append("?");
					if(i < columns.size()-1 ){
						sql.append(",");
						sparam.getTmpSql().append(",");
					}else{
						sql.append(") values (");
						sparam.getTmpSql().append(")");
					}
					tmp = mapRecord.get(columns.get(i).getName().toString());
					if ( "T".equals(columns.get(i).getPrimaryKey())){
						if( !"".equals(pkName))throw new RuntimeException("对照表"+tableName+"[dsid="+dsid+"]只允许有一个主键");
						pkName = columns.get(i).getName();
						sparam.getCvalues().add(UUID32.newGuid());
					}else if ("T".equals(columns.get(i).getIsFK())){
						if( !"".equals(fkName))throw new RuntimeException("对照表"+tableName+"[dsid="+dsid+"]只允许有一个外键");
						fkName = columns.get(i).getName();
						sparam.getCvalues().add(fkid);
					}else{
						if("DS_ID".equalsIgnoreCase(columns.get(i).getName())){
							sparam.getCvalues().add(djdsid);
						}else if ("sin_id".equalsIgnoreCase("columns.get(i).getName()")) {
							sparam.getCvalues().add(sinId);
						}else{
							sparam.getCvalues().add(tmp == null?"":tmp.toString());
						}
					}
				}
			}else{
				//2.sin_id不为空的时候是修改
			}
		}


		if(pkName.equals("") || fkName.equals("")){
			throw new RuntimeException("请设置对照表表["+tableName+"]的主外键");
		}
		//获取关联的键值
		Connection conn = this.getJdbcTemplate().getDataSource().getConnection();
		PreparedStatement stmt = null;
		try {
			if("0".equals(diu)){//添加
				stmt = conn.prepareStatement(sql.append(sparam.getTmpSql()).toString());
				for (int i = 0; i < sparam.getCvalues().size(); i++) {
					stmt.setString(i+1, sparam.getCvalues().get(i));
				}
				stmt.execute();
				returnObject.setInfo(fkid);
				returnObject.setMsg("success");
				//执行后置存储过程

			}else{
				throw new RuntimeException("diu传入数据有误");
			}
		}catch (Exception e) {
			e.printStackTrace();
			throw e;
		}finally{
			if (stmt != null) {
				stmt.close();
			}
			if (conn != null) {
				conn.close();
			}
		}
		return returnObject;
	}



	/******V2.0.0通用保存方法********************************************************************************************/
	@Override
	public ReturnObject saveCommU(ReceiveZM receiveZMobj, HttpSession session,HttpServletRequest request)
	throws Exception {
		Connection conn = null;
		PreparedStatement pstmt = null;
		CallableStatement cstmt = null;
		PreparedStatement pstmtMxAdd = null;
		PreparedStatement pstmtMxUpdate = null;
		PreparedStatement pstmtMxDelete = null;
		ReturnObject returnObject = new ReturnObject();
		String msgs="";
		ReceiveObj zz = receiveZMobj.getZmReceiveObj();//主表信息
		try {
			conn =  this.getJdbcTemplate().getDataSource().getConnection();
			conn.setAutoCommit(false);
			List<ReceiveObj> mz = receiveZMobj.getReceiveObjs();//明细信息
			Long timeS = System.currentTimeMillis();
			//主表的操作（单表的操作）
			DataStore dataStore = new DataStore();
			dataStore = loadDS(zz.getDsid());
			if (dataStore == null) {
				throw new RuntimeException("DSID传入错误,找不到DSID=["+zz.getDsid()+"]的记录");
			}
			Object tableName = dataStore.getUpdateTable();

			if (tableName == null || "".equals(tableName.toString())) {
				throw new RuntimeException("DSID=["+zz.getDsid()+"]没有设置更新的表，请配置");
			}

			StatementParamT sParamT = new StatementParamT();
			String pkValue = UUID32.newGuid();;//设置主表的唯一键值  如果是更新的话，直接覆盖

			//数据库中配置的所有字段
			List<SysColumns> syscolumns = getClns(zz.getDsid());
			//将数据库中的字段缓存为Map
			Map<String, SysColumns> syscolsMap = new HashMap<String, SysColumns>();  // 所有的字段信息   Map<NAME,SysColumns>
			for (int i = 0; i < syscolumns.size(); i++) {
				//排除一对多字段
				if ("T".equals(syscolumns.get(i).getIsMultiClns())) {	//保存一对多数据
					//首先判断一对多保存的时候是保存的Map对象还是外键值
					Object colnVal=zz.getMapRecord().get(syscolumns.get(i).getName());
					if(colnVal!=null){
						boolean a=zz.getMapRecord().get(syscolumns.get(i).getName()) instanceof Map;
						boolean b=zz.getMapRecord().get(syscolumns.get(i).getName()) instanceof String;
						if(b){
							System.out.println("直接保存一对多的外键值");
						}else if(a){
							Map<String, Object> itemsMap = (Map<String,Object>) zz.getMapRecord().get(syscolumns.get(i).getName());
							//把前台传来的一对多的数据转换为java类
							if(itemsMap!=null&&itemsMap.size()>0){
								ReceiveOtM receiveOtM=formatReceiveOtM(itemsMap);
								//调用一对多保存的
								ReturnObject obj=saveCommDGOTM(receiveOtM,session);
								//将 zz.getMapRecord() 覆盖  
								zz.getMapRecord().put(syscolumns.get(i).getName(),obj.getPkValue());
							}
						}
					}
					syscolsMap.put(syscolumns.get(i).getName(), syscolumns.get(i));
				}else {
					syscolsMap.put(syscolumns.get(i).getName(), syscolumns.get(i));
				}
			}
			sParamT = checkZZ(zz.getDiu(),zz.getDsid(),zz.getMapRecord(),session,syscolsMap,pkValue);
			//主表的操作
			if ("success".equals(sParamT.getMsg())) {
				if ("0".equals(zz.getDiu())) {
					//添加
					List<String> cvalueList = sParamT.getCvalues();
					String tmpClnType = "";
					String tmpCname = "";
					pstmt = conn.prepareStatement(sParamT.getSql().toString());
					for (int i = 0;  i < cvalueList.size(); i++) {
						tmpClnType = sParamT.getClnTypeList().get(i);   //类型的集合
						tmpCname = sParamT.getCname().get(i);     //列名的集合
						if ("DATE".equals(tmpClnType)) {
							String dateString=cvalueList.get(i).trim();
							if (cvalueList.get(i)!= null && "".equals(cvalueList.get(i).trim())) {
								pstmt.setString(i+1, "");
							}else {
								pstmt.setTimestamp(i+1, new Timestamp(Long.parseLong(cvalueList.get(i))));
							}
						}else if ("CLOB".equals(tmpClnType)) {
							pstmt.setString(i+1, cvalueList.get(i));
						}else {
							SysColumns columns=syscolsMap.get(tmpCname);
							if(columns!=null){
								if("mulimage".equals(columns.getInputtypeAdd())||"showimage".equals(columns.getInputtypeAdd())){   //如果是多图片上传,那么先上传
									//调用图片上传的保存的方法
									String uid=(String)session.getAttribute(SessionCont.uid);
									Map<String,String> maps=uploadDao.uploadTempImgs(dataStore.getDsId(),tmpCname,uid,session,request);
									pstmt.setString(i+1,maps.get("pkValue"));
									returnObject.setImgErorr(maps.get("error"));
								}else{
									pstmt.setString(i+1, cvalueList.get(i));
								}
							}else{
								pstmt.setString(i+1, cvalueList.get(i));
								System.out.println("=================CommonSaveDaoImpl   #1084 的"+tableName+"表对应的"+tmpCname+"列没有在sys_columns中配置");
							}

						}
					}
					pstmt.execute();
					returnObject.setMsg("success");
					System.out.println("主表保存成功");
				}else if ("1".equals(zz.getDiu())) {
					//更新
					//获取主键的值
					pkValue = sParamT.getMapRecord().get(sParamT.getTablePkName()).toString();
					if (sParamT.getMapRecord().keySet().toArray().length <= 1) {//如果传入的参数只有一个，说明只是主键，所以不需要更新

					}else {
						//获取数据  是否更新记录  系统全局状态位开关
						String upregsql = "select SET_ID,SET_NAME,SET_CODE,SET_VALUE from SYS_SETTING_FLAG WHERE SET_CODE = 'REG001'";
						List<Map<String, Object>> reglList = this.getJdbcTemplate().queryForList(upregsql);

						//						if (reglList != null && !reglList.isEmpty()) {
						if (reglList == null && !reglList.isEmpty()) {
							//记录更新的值
							Object flag = reglList.get(0).get("SET_VALUE");
							if (flag != null && "T".equals(flag.toString())) {
								//获取原值
								Map<String, Object> oldMap = new HashMap<String, Object>();
								Object[] oldCln = sParamT.getMapRecord().keySet().toArray();
								StringBuffer oldSql = new StringBuffer(" select ");
								for (int i = 0; i < oldCln.length; i++) {
									if (!sParamT.getTablePkName().equals(oldCln[i].toString())) {
										oldSql.append(oldCln[i]+",");
									}
								}
								oldSql = new StringBuffer(oldSql.substring(0, oldSql.length()-1));
								oldSql.append(" from "+sParamT.getTableName()+" where "+sParamT.getTablePkName()+"='"+pkValue+"'");
								//借用list<map>
								reglList = this.getJdbcTemplate().queryForList(oldSql.toString());
								if (reglList!= null && !reglList.isEmpty()) {
									oldMap = reglList.get(0);
								}
								Map<String, Object> tmpAftMap = sParamT.getMapRecord();
								tmpAftMap.remove(sParamT.getTablePkName());
								//传入单据  dsid  用户id   单据id 原值      后值   sql
								String procsql = "{Call pk_sys_save.update_log(?,?,?,?,?,?)}";
								cstmt = conn.prepareCall(procsql);
								//(djid,ds_id,value2,out)
								cstmt.setString(1,zz.getDsid());
								cstmt.setString(2,session.getAttribute(SessionCont.uid)==null?"":session.getAttribute(SessionCont.uid).toString());
								cstmt.setString(3,pkValue);
								cstmt.setString(4, tmpAftMap.toString());
								cstmt.setString(5, oldMap.toString());
								cstmt.setString(6, sParamT.getSql().toString());
								cstmt.execute();
							}
						}

						/****
						 * 更新前置存储过程
						 */
						//执行存储过程
						String queryProSql = " SELECT DS_ID,PREFIX,BEFORE_PROC,AFTER_PROC,MEMO FROM SYS_SAVE_PROCEDURES where DS_ID = '"+zz.getDsid()+"'";
						List<Map<String, Object>> procesListM = this.getJdbcTemplate().queryForList(queryProSql);
						Object proc = null;
						if (procesListM != null && !procesListM.isEmpty()) {
							proc = procesListM.get(0).get("BEFORE_PROC");
							if (proc != null && !"".equals(proc)) {
								String procsql = "{Call "+proc+"}";
								cstmt = conn.prepareCall(procsql);
								//(djid,ds_id,value2,out)
								cstmt.setString(1,pkValue);
								cstmt.setString(2,zz.getDsid());
								cstmt.setString(3, zz.getFlag());
								cstmt.setString(4, session.getAttribute(SessionCont.uid)==null?"":session.getAttribute(SessionCont.uid).toString());
								cstmt.registerOutParameter(5,oracle.jdbc.OracleTypes.VARCHAR);
								cstmt.execute();
								returnObject.setInfo(cstmt.getString(5));
								if (!returnObject.getInfo().equals("success")) {
									returnObject.setMsg("success");
								}
							}
						}
						/**
						 * 更新前置存储过程结束
						 */
						List<String> cvalueList = sParamT.getCvalues();   //值的集合
						List<String> cname=sParamT.getCname();            //列名称的集合
						List<String> clnTypeList=sParamT.getClnTypeList(); //列类型的集合

						//	    conn.setAutoCommit(false); //conn为Connection对象
						//创建并实例化一个CLOB对象
						pstmt = conn.prepareStatement(sParamT.getSql().toString());
						System.out.println("====================详情界面修改======#CommonSaveDaoImpl 1162=====:"+sParamT.getSql().toString());
						String tmpCname = "";
						String tmpClnType = "";
						for (int i = 0;  i < cvalueList.size(); i++) {
							tmpClnType = clnTypeList.get(i);
							tmpCname = cname.get(i);     //列名的集合
							if ("DATE".equals(tmpClnType)) {
								if ("".equals(cvalueList.get(i).trim())) {
									pstmt.setString(i+1, "");
								}else {
									System.out.println("---------------------------:"+cvalueList.get(i));
									pstmt.setTimestamp(i+1, new Timestamp(Long.parseLong(cvalueList.get(i))));
								}
							}else if ("CLOB".equals(tmpClnType)) {
								//		CLOB clob = new CLOB((OracleConnection)conn);
								//		   clob = oracle.sql.CLOB.createTemporary((OracleConnection)conn,true,1);
								//		//对CLOB对象赋值
								//		   clob.putString(1,cvalueList.get(i));
								//								Reader clobReader = new StringReader(cvalueList.get(i)); 
								//								pstmt.setCharacterStream(i+1, clobReader);
								//								pstmt.setTimestamp(i+1, new Timestamp(Long.parseLong(cvalueList.get(i))));

								pstmt.setString(i+1, cvalueList.get(i));
								System.out.print(cvalueList.get(i));
							}else {
								SysColumns columns=syscolsMap.get(tmpCname);
								if(columns!=null){
									if("mulimage".equals(columns.getInputtypeAdd())||"showimage".equals(columns.getInputtypeAdd())){   //如果是多图片上传,那么先上传
										//调用图片上传的保存的方法
										String uid=(String)session.getAttribute(SessionCont.uid);
										Map<String,String> maps=uploadDao.uploadTempImgs(dataStore.getDsId(),tmpCname,uid,session,request);
										returnObject.setImgErorr(maps.get("error"));
										//修改的时候直接把chan='T' 原值直接传过来  更新 表中的maps.get("pkValue")=keyValue 的字段的数据 ，如果值等于空值，那么直接把maps.get("pkValue")作为该列的值
										if(cvalueList.get(i)==null||"".equals(cvalueList.get(i))){
											pstmt.setString(i+1, maps.get("pkValue"));
										}else{
											uploadDao.updateLoadImgs(cvalueList.get(i),maps.get("pkValue"));
											pstmt.setString(i+1,cvalueList.get(i));
										}
									}else{
										pstmt.setString(i+1,cvalueList.get(i));
									}
								}else{
									pstmt.setString(i+1, cvalueList.get(i));
									System.out.println("=================CommonSaveDaoImpl   #1219 的"+tableName+"表对应的"+tmpCname+"列没有在sys_columns中配置");
								}
								System.out.print(cvalueList.get(i));
							}
						}
						pstmt.executeUpdate();
						returnObject.setMsg("success");
						//跟新数据for update 再以数据流的形式更新
					}
				}else if ("2".equals(zz.getDiu())) {
					//删除
					//获取主键的值
					pkValue = sParamT.getMapRecord().get(sParamT.getTablePkName()).toString();
					List<String> cvalueList = sParamT.getCvalues();
					String tmpClnType = "";
					pstmt = conn.prepareStatement(sParamT.getSql().toString());
					for (int i = 0;  i < cvalueList.size(); i++) {
						tmpClnType = sParamT.getClnTypeList().get(i);
						if ("DATE".equals(tmpClnType)) {
							pstmt.setTimestamp(i+1, new Timestamp(Long.parseLong(cvalueList.get(i))));
						}else {
							pstmt.setString(i+1, cvalueList.get(i));
						}
					}
					pstmt.execute();
					returnObject.setMsg("success");
				}
			}
			Long timeE = System.currentTimeMillis();
			System.out.println("Cost Time "+ (timeE- timeS) +"mS");
			//明细的操作 开始********************************************************************
			if (mz != null && mz.size() > 0) {
				ReceiveObj mxObj = null;
				StatementParamT mxParamT = new StatementParamT();
				String tmpDsid = "";
				DataStore mxdataStore = null;
				String mztablePkName = "";//明细主键名
				//加载数据库中的所有字段
				List<SysColumns> zmsyscolumns = new ArrayList<SysColumns>();
				//所有的字段类型
				Map<String, String> clnTypeMap = new HashMap<String, String>();
				String waijianName = "";
				//将数据库中的字段缓存为Map
				Map<String, SysColumns> zmsyscolsMap = new HashMap<String, SysColumns>();  // 所有的字段信息   Map<NAME,SysColumns>
				//检查表是不是一个主键      查找数据库的配置 ，是否只有一个主键，表一律不能采用联合主键   主要用户执行存储过程的时候需要用到的后置存储过程
				if(mz.size()>0){
					ReceiveObj	firstMxObj= mz.get(0);
					tmpDsid = firstMxObj.getDsid();
					mxdataStore = loadDS(tmpDsid);
					String tablePk = " select a.constraint_name,  a.column_name from user_cons_columns a, user_constraints b "+
					" where a.constraint_name = b.constraint_name "+
					" and b.constraint_type = 'P' and a.table_name = '"+mxdataStore.getUpdateTable().toUpperCase()+"'";
					List<Map<String, Object>> loadTablePk =  this.getJdbcTemplate().queryForList(tablePk);
					if (loadTablePk == null || loadTablePk.size()!=1) {
						throw new RuntimeException("表["+mxdataStore.getUpdateTable().toUpperCase()+"],没有设置唯一的主键列,不能进行操作" +
								",DSID=["+tmpDsid+"]");
					}
					mztablePkName = loadTablePk.get(0).get("COLUMN_NAME").toString();		
					if (mxdataStore.getUpdateTable() == null || mxdataStore.getUpdateTable().equals("")) {
						throw new RuntimeException("DSID="+tmpDsid+"没有配置更新的表");
					}
					//获取外键
					String waijianSql = " select name from sys_columns where ds_id = '"+firstMxObj.getDsid()+"' and is_fk = 'T' ";
					List<Map<String, Object>> waijianMap = this.getJdbcTemplate().queryForList(waijianSql);
					if (waijianMap != null && !waijianMap.isEmpty()) {
						waijianName = waijianMap.get(0).get("NAME").toString();
					}else {
						throw new RuntimeException("DS_ID="+firstMxObj.getDsid()+"主明细表没有配置外键");
					}
					//获取所有的字段类型
					if(clnTypeMap==null||clnTypeMap.size()==0){
						clnTypeMap = loadAllClnProperty(mxdataStore.getUpdateTable());		//获取所有的字段类型
					}
					zmsyscolumns = getClns(firstMxObj.getDsid());
					for (int m = 0; m < zmsyscolumns.size();m++) {
						zmsyscolsMap.put(zmsyscolumns.get(m).getName(), zmsyscolumns.get(m));
					}
					for(int i = 0;  i < mz.size(); i ++){
						mxObj = mz.get(i);
						mxParamT = checkMZ(mxObj.getDiu(),mxObj.getDsid(),mxObj.getMapRecord(),session,zmsyscolsMap,clnTypeMap,mxdataStore,mztablePkName,UUID32.newGuid(),pkValue,waijianName);
						if ("0".equals(mxObj.getDiu())) {
							if(pstmtMxAdd==null){
								pstmtMxAdd = conn.prepareStatement(mxParamT.getSql().toString());
							}
							//添加明细
							List<String> cvalueList = mxParamT.getCvalues();
							String tmpClnType = "";
							for (int k = 0;  k < cvalueList.size(); k++) {
								tmpClnType = mxParamT.getClnTypeList().get(k);
								if ("DATE".equals(tmpClnType)) {
									pstmtMxAdd.setTimestamp(k+1, new Timestamp(Long.parseLong(cvalueList.get(k)== ""?"0":cvalueList.get(k))));
								}else {
									pstmtMxAdd.setString(k+1,cvalueList.get(k));
								}
							}
							pstmtMxAdd.addBatch();
							System.out.println("明细"+(i+1)+"保存成功");
						}else if ("1".equals(mxObj.getDiu())) {
							if(pstmtMxUpdate==null){
								pstmtMxUpdate = conn.prepareStatement(mxParamT.getSql().toString());
							}
							//更新
							//获取主键的值
							List<String> cvalueList = mxParamT.getCvalues();
							String tmpClnType = "";
							for (int k = 0; k < cvalueList.size(); k++) {
								tmpClnType = mxParamT.getClnTypeList().get(k);
								if ("DATE".equals(tmpClnType)) {
									pstmtMxUpdate.setTimestamp(k+1, new Timestamp(Long.parseLong(cvalueList.get(k)== ""?"0":cvalueList.get(k))));
								}else {
									pstmtMxUpdate.setString(k+1, cvalueList.get(k));
								}
							}
							pstmtMxUpdate.addBatch();
							//returnObject.setMsg("success");
							System.out.println("明细"+i+"更新成功");
						}else if ("2".equals(mxObj.getDiu())) {
							if (mxParamT.getMsg().equals("success")) {
								if(pstmtMxDelete==null){
									pstmtMxDelete = conn.prepareStatement(mxParamT.getSql().toString());
								}
								pstmtMxDelete.setString(1,mxParamT.getTablePkVal());
								pstmtMxDelete.addBatch();
								//	pstmt.setString(1, mxParamT.getCvalues().get(0));
								System.out.println("明细"+i+"删除成功");
							}
						}
					}
					if (pstmtMxAdd!=null){
						int addNos[]=pstmtMxAdd.executeBatch();
					}
					if (pstmtMxUpdate!=null&&!"".equals(pstmtMxUpdate)){
						int updateNos[]=pstmtMxUpdate.executeBatch();  
					}

					if (pstmtMxDelete!=null&&!"".equals(pstmtMxDelete)){
						int deleteNos[]=pstmtMxDelete.executeBatch();  
					}
				}
			}
			if(pstmt!=null){
				pstmt.execute("commit");
			}
			if(pstmtMxAdd!=null){
				pstmtMxAdd.execute("commit");
			}
			if(pstmtMxUpdate!=null){
				pstmtMxUpdate.execute("commit");
			}
			if(pstmtMxDelete!=null){
				pstmtMxDelete.execute("commit");
			}
			//明细操作结束***********************************************************************
			returnObject.setMsg("success");
			//执行存储过程
			String queryProSql = " SELECT DS_ID,PREFIX,BEFORE_PROC,AFTER_PROC,MEMO FROM SYS_SAVE_PROCEDURES where DS_ID = '"+zz.getDsid()+"'";
			List<Map<String, Object>> procesListM = this.getJdbcTemplate().queryForList(queryProSql);
			Object proc = null;
			if (procesListM != null && !procesListM.isEmpty()) {
				proc = procesListM.get(0).get("AFTER_PROC");
				if (proc != null && !"".equals(proc)) {
					String procsql = "{Call "+proc+"}";
					cstmt = conn.prepareCall(procsql);
					cstmt.setString(1,pkValue);
					cstmt.setString(2,zz.getDsid());
					cstmt.setString(3, zz.getFlag());
					System.out.println(pkValue+"======"+zz.getDsid()+"==="+zz.getFlag());
					cstmt.setString(4,session.getAttribute(SessionCont.uid) == null?"":session.getAttribute(SessionCont.uid).toString());
					cstmt.registerOutParameter(5,oracle.jdbc.OracleTypes.VARCHAR);
					cstmt.execute();
					returnObject.setInfo(cstmt.getString(5));
					returnObject.setDsId(zz.getDsid());
					//if (!returnObject.getInfo().equals("success")){
					returnObject.setMsg("success");
					//}
				}
			}
			returnObject.setInfob(new StringBuffer(sParamT.getTablePkName()+"-"+pkValue));
		} catch (SQLException se) {
			se.printStackTrace();
			if(cstmt!=null){
				cstmt.execute("rollback");
			}
			if(pstmt != null){
				pstmt.execute("rollback");
			}
			if(pstmtMxAdd != null){
				pstmtMxAdd.execute("rollback");
			}
			if(pstmtMxUpdate != null){
				pstmtMxUpdate.execute("rollback");
			}
			if(pstmtMxDelete != null){
				pstmtMxDelete.execute("rollback");
			}

			String sbmsgs= se.getMessage();
			String semsgs=sbmsgs.substring(sbmsgs.indexOf(":")+1);
			if(se.getErrorCode()== 1){ //违反唯一约束，还要获取字段，传入存储过程
				String exproc= semsgs.substring(semsgs.indexOf(".")+1,(semsgs.indexOf(")")));//获取违反唯一约束的列名
				//执行存储过程，传入dsId和(exproc违反唯一约束的列名)
				String errSql="{?= call PK_SYS_COM.uf_GetIndexCol(?,?)}";
				cstmt = conn.prepareCall(errSql);  
				cstmt.registerOutParameter(1, Types.VARCHAR);  
				cstmt.setString(2,exproc);
				cstmt.setString(3,zz.getDsid());
				cstmt.execute();
				msgs= cstmt.getString(1);
			}else if(se.getErrorCode()== 20001){
				msgs=se.getMessage().substring(se.getMessage().indexOf("ORA-20001:")+10,se.getMessage().indexOf("ORA-06512"));
			}else{
				msgs=sbmsgs.substring(10, sbmsgs.length());
				if(msgs.indexOf("ORA")!=-1){
					msgs = msgs.substring(0,msgs.indexOf("ORA"));
				}
			}
			returnObject.setMsg("error");
			returnObject.setInfo(msgs);
			conn.setAutoCommit(true);
		}catch (Exception e) {
			//因为执行了commit，所以需要删除保存好的数据 
			//			e.printStackTrace();
			returnObject.setMsg("error");
			if(pstmt != null){
				pstmt.execute("rollback");
			}
			if(pstmtMxAdd != null){
				pstmtMxAdd.execute("rollback");
			}
			if(pstmtMxUpdate != null){
				pstmtMxUpdate.execute("rollback");
			}
			if(pstmtMxDelete != null){
				pstmtMxDelete.execute("rollback");
			}
			if(cstmt!=null){
				cstmt.execute("rollback");
			}
			if("无效的列索引".equals(e.getMessage())){
				//				returnObject.setInfo(e.getMessage()+"[存储过程参数个数不正确]");
				msgs=e.getMessage()+"[存储过程参数个数不正确]";
			}else {
				//				returnObject.setInfo(e.getMessage());
				msgs = e.getMessage();
			}
			e.printStackTrace();
			throw e;
		} finally{
			if (pstmt != null) {
				pstmt.execute("commit");
				pstmt.close();
			}
			if(pstmtMxAdd != null){
				pstmtMxAdd.execute("commit");
				pstmtMxAdd.close();
			}
			if (pstmtMxUpdate != null) {
				pstmtMxUpdate.execute("commit");
				pstmtMxUpdate.close();
			}
			if (pstmtMxDelete != null) {
				pstmtMxDelete.execute("commit");
				pstmtMxDelete.close();
			}
			if (cstmt!= null) {
				cstmt.execute("commit");
				cstmt.close();
			}
			if (conn!=null) {
				conn.commit();
				conn.close();
			}
		}
		return returnObject;
	}

	public StatementParamT checkZZ(String diu,String dsid,Map<String, Object> mapRecord,HttpSession session,Map<String, SysColumns> syscolsMap,String pkValue) throws Exception{
		StatementParamT sparam = new StatementParamT();
		try {
			DataStore dataStore = loadDS(dsid);
			if (dataStore.getUpdateTable() == null || dataStore.getUpdateTable().equals("")) {
				throw new RuntimeException("DSID="+dsid+"没有配置更新的表");
			}
			sparam.setDsId(dsid);
			sparam.setUid((String)session.getAttribute(SessionCont.uid));   //登录人
			//检查表是不是一个主键      查找数据库的配置 ，是否只有一个主键，表一律不能采用联合主键   主要用户执行存储过程的时候需要用到的后置存储过程
			String tablePk = " select a.constraint_name,  a.column_name from user_cons_columns a, user_constraints b "+
			" where a.constraint_name = b.constraint_name "+
			" and b.constraint_type = 'P' and a.table_name = '"+dataStore.getUpdateTable().toUpperCase()+"'";
			List<Map<String, Object>> loadTablePk =  this.getJdbcTemplate().queryForList(tablePk);
			if (loadTablePk == null || loadTablePk.size()!=1) {
				throw new RuntimeException("表["+dataStore.getUpdateTable().toUpperCase()+"],没有设置唯一的主键列,不能进行操作" +
						",DSID=["+dsid+"]");
			}

			String tablePkName = loadTablePk.get(0).get("COLUMN_NAME").toString();		
			//获取所有的字段类型
			Map<String, String> clnTypeMap = new HashMap<String, String>();
			clnTypeMap = loadAllClnProperty(dataStore.getUpdateTable());		//获取所有的字段类型
			sparam.setClnType(clnTypeMap);

			//追加修改人,修改日期
			mapRecord.put("LAST_MOD_MAN", sparam.getUid());
			mapRecord.put("LAST_MOD_DATE", new Date().getTime());

			//如果不是本表的字段全部移除
			Object[] jmMap = mapRecord.keySet().toArray();
			for (int i = 0; i < jmMap.length; i++) {
				if (!clnTypeMap.containsKey(jmMap[i].toString())) {
					mapRecord.remove(jmMap[i].toString());
				}
			}
			//将界面的传入值返回
			sparam.setMapRecord(mapRecord);
			if ("0".equals(diu)) { //添加
				sparam.getSql().append(" insert into "+dataStore.getUpdateTable()+" (");
				sparam.getTmpSql().append(" values (");
				//获取有必须填写的字段
				List<SysColumns> needCln = getNeedClns(dsid);
				for(int i = 0; i < needCln.size(); i ++){
					if (!(mapRecord.containsKey(needCln.get(i).getName()))) {
						mapRecord.put(needCln.get(i).getName(), "");
					}
				}
				//如果没有主键 ，则将主键也加入
				if (!mapRecord.containsKey(tablePkName)) {
					mapRecord.put(tablePkName, "");
				}
				sparam.setTablePkName(tablePkName);
				sparam.setMapRecord(mapRecord);
				jmMap = mapRecord.keySet().toArray();

				String tmpCln = "";
				for(int i = 0; i < jmMap.length; i ++){
					sparam.getSql().append(jmMap[i].toString());
					sparam.getTmpSql().append("?");
					if(tablePkName.equals(jmMap[i].toString())) {
						sparam.getClnTypeList().add("VARCHAR2");
						sparam.getCvalues().add(pkValue);
						sparam.getCname().add(tablePkName);
					}else {
						sparam.getClnTypeList().add(clnTypeMap.get(jmMap[i]).toString());
						sparam.getCvalues().add(getDClnValues(dsid,jmMap[i].toString(),syscolsMap.get(jmMap[i]),clnTypeMap,session,true,mapRecord));
						sparam.getCname().add(jmMap[i].toString());
					}
					if (i < jmMap.length - 1) {
						sparam.getSql().append(",");
						sparam.getTmpSql().append(",");
					}else {
						sparam.getSql().append(")");
						sparam.getTmpSql().append(")");
					}
				}
				sparam.getSql().append(sparam.getTmpSql());
				sparam.setTablePkName(tablePkName);
				sparam.setDjId(pkValue);
				sparam.setMsg("success");
			}else if ("1".equals(diu)) {//更新
				//如果是更新，要传入主键
				if (!mapRecord.containsKey(tablePkName)) {
					throw new RuntimeException("没有传入主键值无法修改");
				}
				//拼接更新值
				sparam.getSql().append(" update "+ dataStore.getUpdateTable() +" set ");

				jmMap = mapRecord.keySet().toArray();
				for(int i = 0; i < jmMap.length; i ++){
					if(tablePkName.equals(jmMap[i].toString())){
					}else{
						sparam.getSql().append(jmMap[i].toString()+"=?,");
						sparam.getClnTypeList().add(clnTypeMap.get(jmMap[i].toString()));
						sparam.getCvalues().add(getDClnValuesUpdate(dsid,jmMap[i].toString(),syscolsMap.get(jmMap[i]),clnTypeMap,session,true,mapRecord));
						sparam.getCname().add(jmMap[i].toString());
					}
				}
				sparam.setSql(new StringBuffer(sparam.getSql().substring(0, sparam.getSql().toString().length()-1)));
				sparam.getSql().append(" where "+tablePkName+"=? ");
				sparam.getClnTypeList().add(clnTypeMap.get(tablePkName));
				sparam.getCvalues().add(mapRecord.get(tablePkName).toString());
				sparam.getCname().add(tablePkName.toString());
				sparam.setTablePkName(tablePkName);
				sparam.setDjId(mapRecord.get(tablePkName).toString());
			}else if ("2".equals(diu)) {//删除
				//如果是删除，要传入主键
				throw new RuntimeException("主表不允许删除，只允许作废");
			}
			System.out.println("********************"+sparam.getCvalues().size()+"=="+sparam.getClnTypeList().size()+"=="+sparam.getCname().size());
			sparam.setTableName(dataStore.getUpdateTable());
			sparam.setMsg("success");
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
		return sparam;
	}





	/***
	 * 校验明细的数据
	 * @param diu
	 * @param dsid
	 * @param mapRecord  js中传入的明细数据
	 * @param session
	 * @param syscolsMap  所有的列（根据DSID查询的sys_columns）
	 * @param clnTypeMap  所有列的类型
	 * @param dataStore
	 * @param tablePkName
	 * @param pkValue
	 * @param zpkValue 主表的键值
	 * @return
	 * @throws Exception
	 * @author Xuzq
	 * @date 2014-5-30 下午02:00:49
	 */
	public StatementParamT checkMZ(String diu,String dsid,Map<String, Object> mapRecord,HttpSession session,
			Map<String, SysColumns> syscolsMap,Map<String, String> clnTypeMap,DataStore dataStore, String tablePkName,String pkValue,String zPkvalue,String wjName) throws Exception{
		StatementParamT sparam = new StatementParamT();
		try {
			//如果不是本表的字段全部移除
			Object[] jmMap = mapRecord.keySet().toArray();
			for (int i = 0; i < jmMap.length; i++) {
				if(!clnTypeMap.containsKey(jmMap[i].toString())){
					mapRecord.remove(jmMap[i].toString());
				}
			}
			sparam.setDsId(dsid);
			sparam.setUid((String)session.getAttribute(SessionCont.uid));   //登录人
			String logSql="SELECT s.name FROM sys_columns s WHERE s.ds_id='"+dsid+"' AND s.is_log='T'";
			List<Map<String, Object>> recordLogColns =  this.getJdbcTemplate().queryForList(logSql);
			sparam.setRecordLogColns(recordLogColns);
			//将界面的传入值返回
			sparam.setMapRecord(mapRecord);
			if ("0".equals(diu)) { //添加
				sparam.getSql().append(" insert into "+dataStore.getUpdateTable()+" (");
				sparam.getTmpSql().append(" values (");
				//获取有必须填写的字段
				List<SysColumns> needCln = getNeedClns(dsid);
				for(int i = 0; i < needCln.size(); i ++){
					if(!clnTypeMap.containsKey(needCln.get(i).getName())){
						continue;
					}
					if (!(mapRecord.containsKey(needCln.get(i).getName()))) {
						mapRecord.put(needCln.get(i).getName(),"");
					}
				}
				//如果没有主键 ，则将主键也加入
				if (!mapRecord.containsKey(tablePkName)){
					mapRecord.put(tablePkName,"");
				}
				//如果没有外键 ，则将外键 也加入
				if (!mapRecord.containsKey(wjName)) {
					mapRecord.put(wjName,"");
				}
				sparam.setTablePkName(tablePkName);
				sparam.setMapRecord(mapRecord);
				jmMap = mapRecord.keySet().toArray();
				String tmpCln = "";
				for(int i = 0; i < jmMap.length; i++){
					sparam.getSql().append(jmMap[i].toString());
					sparam.getTmpSql().append("?");
					if (tablePkName.equals(jmMap[i].toString())) {
						sparam.getClnTypeList().add("VARCHAR2");
						sparam.getCvalues().add(pkValue);
						sparam.getCname().add(tablePkName);
					}else if(wjName.equals(jmMap[i].toString())){
						sparam.getClnTypeList().add("VARCHAR2");
						sparam.getCvalues().add(zPkvalue);
						sparam.getCname().add(jmMap[i].toString());
					}else{
						sparam.getClnTypeList().add(clnTypeMap.get(jmMap[i]).toString());
						sparam.getCvalues().add(getDClnValues(dsid,jmMap[i].toString(),syscolsMap.get(jmMap[i]),clnTypeMap,session,true,mapRecord));
						sparam.getCname().add(jmMap[i].toString());		
					}
					if (i < jmMap.length - 1) {
						sparam.getSql().append(",");
						sparam.getTmpSql().append(",");
					}else {
						sparam.getSql().append(")");
						sparam.getTmpSql().append(")");
					}
				}
				sparam.getSql().append(sparam.getTmpSql());
				sparam.setMsg("success");
				sparam.setDjId(pkValue);
				sparam.setTablePkName(tablePkName);
			}else if ("1".equals(diu)) {//更新
				//如果是更新，要传入主键
				if (!mapRecord.containsKey(tablePkName)) {
					throw new RuntimeException("没有传入主键值无法修改");
				}
				//拼接更新值
				sparam.getSql().append(" update "+ dataStore.getUpdateTable() +" set ");
				jmMap = mapRecord.keySet().toArray();
				for(int i = 0; i < jmMap.length; i ++){
					if(tablePkName.equals(jmMap[i].toString())){
					}else{
						sparam.getSql().append(jmMap[i].toString()+"=?,");
						sparam.getCvalues().add(mapRecord.get(jmMap[i])==null?"":mapRecord.get(jmMap[i]).toString());
						sparam.getCname().add(jmMap[i].toString());
						sparam.getClnTypeList().add(clnTypeMap.get(jmMap[i].toString()));
					}
				}
				sparam.setSql(new StringBuffer(sparam.getSql().substring(0,sparam.getSql().toString().length()-1)));
				sparam.getSql().append(" where "+tablePkName+"=? ");
				sparam.getClnTypeList().add(clnTypeMap.get(tablePkName));
				sparam.getCvalues().add(mapRecord.get(tablePkName).toString());
				sparam.getCname().add(tablePkName.toString());
				sparam.setTablePkName(tablePkName);
				sparam.setDjId(mapRecord.get(tablePkName).toString());
			}else if ("2".equals(diu)) {//删除
				//如果是删除，要传入主键
				if (!mapRecord.containsKey(tablePkName)) {
					throw new RuntimeException("没有传入主键值无法删除");
				}
				String sql = "select count(1) from " + dataStore.getUpdateTable() +" where  "+tablePkName+"='"+mapRecord.get(tablePkName)+"'";
				if (this.getJdbcTemplate().queryForInt(sql) <= 1) {
					//拼接更新值
					sparam.getSql().append(" delete  from "+  dataStore.getUpdateTable() +" where  ");
					sparam.getSql().append(" "+tablePkName+"=? ");
					sparam.setTablePkName(tablePkName);
					sparam.setTablePkVal((String) mapRecord.get(tablePkName));
				}else{
					sparam.setMsg("fail");
				}				
			}
			if (sparam.getMsg().equals("fail")) {
			}else {
				sparam.setMsg("success");
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
		return sparam;
	}




	//获取所有字段
	public List<SysColumns> getNeedClns(String dsid){
		List<SysColumns> columns = new ArrayList<SysColumns>();
		Query query = this.getSessionFactory().getCurrentSession().createQuery("from SysColumns sc where sc.dsid = ? and sc.defaultValueAdd is not null ").setString(0, dsid);
		columns = query.list();
		return columns;
	}

	//加载所有键值的类型
	public Map<String, String> loadAllClnProperty(String tableName) throws Exception{
		Connection conn=null;
		PreparedStatement stmt = null;
		List<Map<String, Object>> clnPro = null;
		Map<String, String> map = new HashMap<String, String>();
		try {
			conn = this.getJdbcTemplate().getDataSource().getConnection();
			//DATE  VARCHAR2 NUMBER CHAR
			clnPro = this.getJdbcTemplate().queryForList("select DATA_TYPE,COLUMN_NAME from ALL_TAB_COLUMNS where  table_name = '"+tableName.toUpperCase()+"' AND OWNER IN (select MAX(USERNAME) from user_role_privs) ");

			for (int i = 0; i < clnPro.size(); i++) {
				map.put(clnPro.get(i).get("COLUMN_NAME").toString(),clnPro.get(i).get("DATA_TYPE").toString());
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}finally{
			if (stmt != null) {
				stmt.close();
			}
			if (conn != null) {
				conn.close();
			}
		}
		return map;
	}

	/*******
	 *  添加的时候   设置默认值规则V2.0.0
	 *  defaultValue   $uid   $name $uid   $depid   $staid
	 *  			   C- xx   常量
	 *  			   F- xx   ORACLE方法  IN_VALUE 
	 *  			   P- xx   ORACLE存储过程  IN_VALUE  OUT_VALUE
	 *  			   D- xxx	定制编号  F001
	 * @param oldValues	原值
	 * @param clnName 字段名
	 * @param column 字段的参数
	 * @param clnTypeMap 所有字段数据库中的类型
	 * @param flag     false 为前台传入 true 为系统默认
	 * @return
	 * @author Xuzq
	 * @date 2014-5-29 下午02:30:26
	 ***************************************************************************/
	//																																		     传入的参数
	public String getDClnValues(String dsid,String clnName,SysColumns column,Map clnTypeMap,HttpSession session,boolean flag,Map<String, Object> mapRecord) throws Exception{
		String newValue = "";
		Object typeName = clnTypeMap.get(clnName);
		Object oldValues = mapRecord.get(clnName);
		//特殊MD5加密处理
		if(dsid.equals("ds_bs_operators") && clnName.equals("O_PASS_WORD")){
			return MD5Util.encode(oldValues.toString()==null?"":oldValues.toString());
		}
		Object tmp = null;
		System.out.println("CommonSaveImpl #L1532"+column);
		if(column==null){
			return newValue;
		}
		Object defaultObj = column.getDefaultValueAdd();

		String defaultValue = "";
		if (defaultObj != null) {
			defaultValue = defaultObj.toString();
		}
		if (("DATE").equals(typeName.toString())) { //如果字段是日期类型
			if (defaultValue !=null && defaultValue.indexOf("$") == 0) {
				//date 是数据库中的配置  
				if ("date".equals(defaultValue.substring(1, defaultValue.toString().length())) ) {   
					newValue = (oldValues!=null && !"".equals(oldValues.toString())) ? oldValues.toString(): System.currentTimeMillis()/1000*1000+"";
				}
			}else {
				newValue = (oldValues!=null && !"".equals(oldValues.toString())) ? oldValues.toString():"";
			}
		}else {  //如果字段不是日期类型
			if (defaultValue !=null && defaultValue.indexOf("$") == 0) {
				//字段不是日期类型   同时排出 默认值为  date 
				if (!"date".equals(defaultValue.substring(1, defaultValue.toString().length())) ) {
					tmp =  session.getAttribute(defaultValue.substring(1,defaultValue.length()));
					newValue = (tmp == null)?"":tmp.toString();
				}
				System.out.println("默认字段值"+newValue);

			}else if (defaultValue !=null && defaultValue.indexOf("D")  == 0) {
				//定制方法 F001  个性定制方法  获取流水号编码
				//		  F002  将字符串加密
				System.out.println(dsid+"==========定制方法   F001 L.543");
				if (defaultValue.substring(2,defaultValue.length()).equalsIgnoreCase("F001")) {
					//获取数据库指定字符串
					Object stationId = session.getAttribute(SessionCont.STATION_ID);
					if (stationId == null) {
						throw new RuntimeException("session中没有站点信息,没有登录或者联系开发");
					}
					newValue = getCodeStr(dsid,stationId.toString(),"1");
				}else if(defaultValue.substring(2,defaultValue.length()).equalsIgnoreCase("F002")){
					//将字符串加密
					newValue = MD5Util.encode(oldValues==null?"":oldValues.toString());
				}
			}else if (defaultValue !=null && defaultValue.indexOf("C")  == 0) {
				//常量
				if(oldValues == null || "".equals(oldValues.toString())){
					newValue = defaultValue.substring(2,defaultValue.length());
				}else {
					newValue = oldValues.toString();
				}
			}else{
				newValue = oldValues==null?"":oldValues.toString();
			}
		}
		return newValue;
	}



	/***
	 *  更新的时候   设置默认值规则V2.0.0   getDClnValuesUpdate
	 *  defaultValue   $uid   $name $uid   $depid   $staid
	 *  			   C- xx   常量
	 *  			   F- xx   ORACLE方法  IN_VALUE 
	 *  			   P- xx   ORACLE存储过程  IN_VALUE  OUT_VALUE
	 *  			   D- xxx	定制编号  F001
	 * @param oldValues	原值
	 * @param clnName 字段名
	 * @param column 字段的参数
	 * @param clnTypeMap 所有字段数据库中的类型
	 * @param flag     false 为前台传入 true 为系统默认
	 * @return
	 * @author Xuzq
	 * @date 2014-5-29 下午02:30:26
	 ***************************************************************************/
	//																																		     传入的参数
	public String getDClnValuesUpdate(String dsid,String clnName,SysColumns column,Map clnTypeMap,HttpSession session,boolean flag,Map<String, Object> mapRecord) throws Exception{
		/***
		 * 注意：目前存在前端输入值，但是有可能存在被默认值覆盖的情况，注意优化
		 */

		String newValue = "";
		Object typeName = clnTypeMap.get(clnName);   //字段的类型
		Object oldValues = mapRecord.get(clnName);   //该字段的输入的值
		//特殊MD5加密处理
		if(dsid.equals("ds_bs_operators") && clnName.equals("O_PASS_WORD")){
			return MD5Util.encode(oldValues.toString()==null?"":oldValues.toString());
		}

		Object tmp = null;
		System.out.println("CommonSaveImpl #L1532"+column);
		if(column==null){
			return newValue;
		}
		Object defaultObj = column.getDefaultValueAdd();   //该字段的默认值

		String defaultValue = "";
		if (defaultObj != null) {
			defaultValue = defaultObj.toString();
		}
		if (("DATE").equals(typeName.toString())) { //如果字段是日期类型
			newValue = (oldValues!=null && !"".equals(oldValues.toString())) ? oldValues.toString():"";
		}else {  //如果字段不是日期类型
			if (defaultValue !=null && defaultValue.indexOf("$") == 0) {
				//字段不是日期类型   同时排出 默认值为  date 
				if (!"date".equals(defaultValue.substring(1, defaultValue.toString().length())) ) {
					tmp =  session.getAttribute(defaultValue.substring(1,defaultValue.length()));
					newValue = (tmp == null)?"":tmp.toString();
					newValue = (oldValues!=null && !"".equals(oldValues.toString())) ? oldValues.toString():newValue;
				}
				System.out.println("默认字段值"+newValue);
			}else if (defaultValue !=null && defaultValue.indexOf("D")  == 0) {
				//定制方法 F001  个性定制方法  获取流水号编码
				//		  F002  将字符串加密
				System.out.println(dsid+"==========定制方法   F001 L.543");
				if (defaultValue.substring(2,defaultValue.length()).equalsIgnoreCase("F001")) {
					//获取数据库指定字符串
					Object stationId = session.getAttribute(SessionCont.STATION_ID);
					if (stationId == null) {
						throw new RuntimeException("session中没有站点信息,没有登录或者联系开发");
					}
					newValue = getCodeStr(dsid,stationId.toString(),"1");
				}else if(defaultValue.substring(2,defaultValue.length()).equalsIgnoreCase("F002")){
					//将字符串加密
					newValue = MD5Util.encode(oldValues==null?"":oldValues.toString());
				}
			}else if (defaultValue !=null && defaultValue.indexOf("C")  == 0) {
				//常量
				if(oldValues == null || "".equals(oldValues.toString())){
					newValue = defaultValue.substring(2,defaultValue.length());
				}else {
					newValue = oldValues.toString();
				}
			}else{
				newValue = oldValues==null?"":oldValues.toString();
			}
		}
		return newValue;
	}









	/***
	 * 获取所有的字段
	 * @param dsid
	 * @return
	 * @author Xuzq
	 * @date 2014-5-29 下午03:58:53
	 */
	//获取所有字段
	public List<SysColumns> getClns(String dsid){
		List<SysColumns> columns = new ArrayList<SysColumns>();
		Query query = this.getSessionFactory().getCurrentSession().createQuery("from SysColumns sc where sc.dsid = ? ").setString(0, dsid);
		columns = query.list();
		return columns;
	}
	public void test1(){
		Map<String, String> record = new HashMap<String, String>();
		record.put("XTDE", "AAAAAAAAAAAA");
		record.put("DDDD", "上海");

		System.out.println(record.toString());
	}


	/***
	 * 保存通用的列表信息，像保存选题计划等。。。
	 */
	@Override
	public ReturnObject saveCommL(ReceiveList receiveList, HttpSession session)
	throws Exception {
		ReturnObject returnObject = new ReturnObject();
		String pkName = receiveList.getPkName();
		String fkVal = receiveList.getFkVal();
		String fkName = receiveList.getFkName();

		if (pkName == null || pkName.equals("") || 
				fkVal == null || fkVal.equals("") || 
				fkName == null || fkName.equals("")) {
			throw new RuntimeException("没有传入外键，操作失败，请联系开发");
		}

		Connection conn  = this.getJdbcTemplate().getDataSource().getConnection();
		PreparedStatement pstmt = null;
		try {
			List<ReceiveObj> upObjs = receiveList.getReceiveObjs();
			String dsid = "";
			ReceiveObj tmpObj = null;

			//查找表中的所有字段
			List<SysColumns> dbAllColumns = new ArrayList<SysColumns>();
			//将表中的字段转成Map
			Map<String, SysColumns> colMap = new HashMap<String, SysColumns>();
			Map<String, String> colTypeMap = new HashMap<String, String>();

			DataStore dataStore = null;
			StringBuffer tmpSql = new StringBuffer(); 
			String realPkName = "";
			String tablePkSql = "";
			List<Map<String, Object>> loadTablePk =  new ArrayList<Map<String,Object>>();

			StatementParamT spaParamT = new StatementParamT();

			for (int i = 0; i < upObjs.size(); i++) {
				//清空对应的信息
				tmpSql = new StringBuffer(); 
				spaParamT = new StatementParamT();

				tmpObj = upObjs.get(i);

				if (!dsid.equals(tmpObj.getDsid())) {
					dsid = tmpObj.getDsid();
					dataStore = loadDS(dsid);
					colTypeMap = loadAllClnProperty(dataStore.getUpdateTable());
					tablePkSql = " select a.constraint_name,  a.column_name from user_cons_columns a, user_constraints b "+
					" where a.constraint_name = b.constraint_name "+
					" and b.constraint_type = 'P' and a.table_name = '"+dataStore.getUpdateTable().toUpperCase()+"'";
					loadTablePk =  this.getJdbcTemplate().queryForList(tablePkSql);
					if (loadTablePk == null || loadTablePk.size()!=1) {
						throw new RuntimeException("表["+dataStore.getUpdateTable().toUpperCase()+"],没有设置唯一的主键列,不能进行操作" +
								",DSID=["+dsid+"]");
					}
					realPkName = loadTablePk.get(0).get("COLUMN_NAME").toString();		

					if (!realPkName.equals(pkName)) {
						throw new RuntimeException("传入的主键字段  和 "+dataStore.getUpdateTable().toUpperCase()+"表的  主键字段不统一   ");
					}

					//加载对应的数据信息
					dbAllColumns = loadColumns(dsid);
					for(int k = 0 ; k < dbAllColumns.size(); k ++){
						if (colTypeMap.containsKey(dbAllColumns.get(k).getName())) {
							colMap.put(dbAllColumns.get(k).getName(), dbAllColumns.get(k));
						}
					}
				}
				//移除非本表字段
				Object[] mapSet = tmpObj.getMapRecord().keySet().toArray();
				for(int m = 0; m < mapSet.length; m++){
					if (!colTypeMap.containsKey(mapSet[m])) {
						tmpObj.getMapRecord().remove(mapSet[m]);
					}
				}
				//getDClnValues(String dsid,String clnName,SysColumns column,Map clnTypeMap,HttpSession session,boolean flag,Map<String, Object> mapRecord)
				if ("0".equals(tmpObj.getDiu())) {
					//添加
					tmpObj.getMapRecord().remove(pkName);
					if (!tmpObj.getMapRecord().containsKey(fkName)) {
						tmpObj.getMapRecord().put(fkName, fkVal);
					}
					spaParamT.getSql().append(" insert into "+dataStore.getUpdateTable()+" ( ");
					spaParamT.getTmpSql().append(" values (");
					mapSet = tmpObj.getMapRecord().keySet().toArray();
					for (int j = 0; j < mapSet.length; j++) {
						spaParamT.getSql().append(mapSet[j].toString());
						spaParamT.getCvalues().add(tmpObj.getMapRecord().get(mapSet[j])==null?"":tmpObj.getMapRecord().get(mapSet[j]).toString());
						spaParamT.getTmpSql().append("?");
						if (j < mapSet.length - 1) {
							spaParamT.getSql().append(",");
							spaParamT.getTmpSql().append(",");
						}else {
							spaParamT.getSql().append(")");
							spaParamT.getTmpSql().append(")");
						}
					}
					spaParamT.getSql().append(spaParamT.getTmpSql());//拼接sql语句
					pstmt = conn.prepareStatement(spaParamT.getSql().toString());
					System.out.println("CommonSaveDaoImpl #L.1764# "+ spaParamT.getSql().toString());
					for(int n = 0; n < mapSet.length; n++){
						if ("DATE".equals(colTypeMap.get(mapSet[n]))) {
							if (tmpObj.getMapRecord().get(mapSet[n]) == null || "".equals(tmpObj.getMapRecord().get(mapSet[n]))) {
								//为空的时候要判断有没有默认值，有的话添加默认值
								pstmt.setTimestamp(n+1, new Timestamp(System.currentTimeMillis()));
							}else {
								pstmt.setTimestamp(n+1, new Timestamp(Long.parseLong(tmpObj.getMapRecord().get(mapSet[n]) == null?"":tmpObj.getMapRecord().get(mapSet[n]).toString())));
							}

						}else {
							if (pkName.equals(mapSet[n].toString())) {
								pstmt.setString(n+1, UUID32.newGuid());
							}else {
								pstmt.setString(n+1, spaParamT.getCvalues().get(n));
							}
						}
					}
					pstmt.execute();
					pstmt.close();
				}else if ("1".equals(tmpObj.getDiu())) {
					//更新
					if (!tmpObj.getMapRecord().containsKey(pkName)) {
						throw new RuntimeException("更新的记录没有传入主键，无法更新");
					}
					spaParamT.getSql().append(" update "+dataStore.getUpdateTable()+" set ");
					spaParamT.getTmpSql().append(" where "+pkName+"='"+tmpObj.getMapRecord().get(pkName).toString()+"'");
					//移除主键
					tmpObj.getMapRecord().remove(pkName);
					mapSet = tmpObj.getMapRecord().keySet().toArray();
					for (int j = 0; j < mapSet.length; j++) {
						spaParamT.getSql().append(mapSet[j]+"=?");
						spaParamT.getCvalues().add(tmpObj.getMapRecord().get(mapSet[j])== null?"":tmpObj.getMapRecord().get(mapSet[j]).toString());
						if (j < mapSet.length - 1) {
							spaParamT.getSql().append(",");
						}
					}
					pstmt = conn.prepareStatement(spaParamT.getSql().toString() + spaParamT.getTmpSql().toString());
					System.out.println("CommonSaveDaoImpl #L.1802# "+ spaParamT.getSql().toString() + spaParamT.getTmpSql().toString());
					System.out.println("参数赋值");
					for(int j = 0; j < mapSet.length; j++){
						if ("DATE".equalsIgnoreCase(colTypeMap.get(mapSet[j]))) {
							if("".equals(spaParamT.getCvalues().get(j))||spaParamT.getCvalues().get(j)==null){
								pstmt.setTimestamp(j+1, new Timestamp(System.currentTimeMillis()));
							}else{
								pstmt.setTimestamp(j+1, new Timestamp(Long.parseLong(spaParamT.getCvalues().get(j).equals("")
										?System.currentTimeMillis()/1000*1000+"":spaParamT.getCvalues().get(j) ) ));
							}
						}else {
							pstmt.setString(j+1,spaParamT.getCvalues().get(j));
						}
						System.out.print(spaParamT.getCvalues().get(j)+" | ");
					}
					pstmt.executeUpdate();
					pstmt.close();
				}else if ("2".equals(tmpObj.getDiu())) {
					//删除
					Object pkVal = tmpObj.getMapRecord().get(pkName);
					if (pkVal == null || "".equals(pkVal)) {
						throw new RuntimeException("要删除的记录没有传入主键"+pkName);
					}else {
						tmpSql.append(" delete from "+dataStore.getUpdateTable() +" where "+realPkName+"='"+pkVal.toString()+"'");
						System.out.println("tmpSql.toString():"+tmpSql.toString());
					}
					pstmt = conn.prepareStatement(tmpSql.toString());
					pstmt.executeUpdate();
					pstmt.close();
				}
			}
			returnObject.setMsg("success");
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}finally{
			if (pstmt != null) {
				pstmt.close();
			}
			if (conn!=null) {
				conn.close();
			}
		}
		return returnObject;
	}


	/***
	 *一对多的map对象转换成一对多的ReceiveOtM实体类对象
	 * @param itemsMap
	 * @return
	 */
	public ReceiveOtM formatReceiveOtM(Map<String, Object> itemsMap){
		//dataList={"diu":"0","dsId":dsid,"sinId":"","coluname":coluname,"sameDsid":sameDsid,"rows":selectRows};
		ReceiveOtM r = new ReceiveOtM();
		if (itemsMap.containsKey("diu")) {
			r.setDiu((String)itemsMap.get("diu"));
		}if (itemsMap.containsKey("dsId")) {
			r.setDsId((String) itemsMap.get("dsId"));
		}if(itemsMap.containsKey("sinId")){
			r.setSinId((String)itemsMap.get("sinId"));
		}if (itemsMap.containsKey("coluname")) {
			r.setColumnName((String)itemsMap.get("coluname"));
		}if (itemsMap.containsKey("sameDsid")) {
			r.setSameDsid((String)itemsMap.get("sameDsid"));
		}if (itemsMap.containsKey("rows")) {
			r.setRows((List<Map<String, Object>>)itemsMap.get("rows"));
		}if(itemsMap.containsKey("multidsid")){
			r.setDjdsid((String)itemsMap.get("multidsid"));
		}
		return r;
	}




	/****
	 * omObj
	 * 保存一对多的方法
	 */
	@Override
	public ReturnObject saveCommDGOTM(ReceiveOtM omObj, HttpSession session) throws Exception {
		ReturnObject returnObject = new ReturnObject();
		Connection conn = null;
		PreparedStatement stmt= null;
		String pkName="";
		String sinId = omObj.getSinId();  //主键值
		try {
			//本表的信息
			String dsid = omObj.getDsId();
			String columnName = omObj.getColumnName();
			//用于存储一对多表的dsid  如果没有配置，默认采用本表的dsid
			String sameDsid = omObj.getSameDsid();
			if (sameDsid == null || "".equals(sameDsid.trim())) {
				sameDsid=dsid ;
			}
			//关联单据的信息
			String djdsid = omObj.getDjdsid();
			//获取一对多关联的外键名
			String mulsql="select * from sys_columns s where s.DS_ID='"+dsid+"' and  s.NAME='"+columnName+"'";
			List<Map<String, Object>> mulDataColn=this.jdbcTemplate.queryForList(mulsql);
			if(mulDataColn == null || mulDataColn.isEmpty() 
					|| mulDataColn.get(0).get("MULTI_CLNS_FK") == null 
					|| "".equals(mulDataColn.get(0).get("MULTI_CLNS_FK").toString())){
				throw new RuntimeException("没有找到关联的对照信息,或者关联信息的表为空[columnName="+columnName+"]");
			}
			//与第三张表关联的外键名
			pkName = (String) mulDataColn.get(0).get("MULTI_CLNS_FK");  //存对照的id

			//获取关联表名
			String tableSql = "select UPDATE_TABLE from sys_datastore WHERE DS_ID = '"+djdsid+"'";  //一对多表的dsid
			List<Map<String, Object>> tmpMapList = this.getJdbcTemplate().queryForList(tableSql);
			if(tmpMapList == null || tmpMapList.isEmpty() 
					|| tmpMapList.get(0).get("UPDATE_TABLE") == null 
					|| "".equals(tmpMapList.get(0).get("UPDATE_TABLE").toString())){
				throw new RuntimeException("没有找到关联的对照信息,或者关联信息的表为空[DSID="+djdsid+"]");
			}
			String tableName = (String) tmpMapList.get(0).get("UPDATE_TABLE");
			conn = this.getJdbcTemplate().getDataSource().getConnection();
			//前台传入的数据
			List<Map<String, Object>> recordList = new ArrayList<Map<String,Object>>();
			recordList = omObj.getRows();

			//添加数据
			StringBuffer lastSql = new StringBuffer();
			//获取本表的所有字段
			Map<String, String> clnTypeMap = new HashMap<String, String>();
			clnTypeMap = loadAllClnProperty(tableName);		//获取所有的字段类型和字段名

			//将关联表中的数据删除
			String pkStrTmp = "";
			if (sinId != null && !"".equals(sinId)) {
				String sql = " delete FROM "+tableName+" WHERE "+pkName+"='"+sinId+"'";   
				conn.createStatement().execute(sql);
				pkStrTmp = sinId;
			}else {
				pkStrTmp = UUID32.newGuid();
				sinId=pkStrTmp;
			}


			Object[] mapSet = null; //所有字段的缓存
			StatementParamT sparamT =null;//参数缓存对象
			//设置值  执行
			for(int i = 0; i < recordList.size(); i ++){
				String pkId=(String) recordList.get(i).get("ID");  //判断传递的行数据是否有主键值
				mapSet = recordList.get(i).keySet().toArray();
				sparamT = new StatementParamT();//参数缓存对象
				lastSql = new StringBuffer(); //语句缓存
				if(pkId==null||"".equals(pkId)){
					pkId=UUID32.newGuid();
				}
				sparamT.getSql().append(" insert into "+tableName +" (");
				sparamT.getTmpSql().append(" ) values (");
				//将不是本表字段移除
				for(int m = 0; m <mapSet.length ; m++){
					if(!clnTypeMap.containsKey(mapSet[m])){
						recordList.get(i).remove(mapSet[m]);
						continue;
					}else{
						sparamT.getSql().append(mapSet[m]+",");
						sparamT.getTmpSql().append("?,");
						if(pkName.equals(mapSet[m].toString())){
							sparamT.getCvalues().add(pkStrTmp);
						}else if("DS_ID".equals(mapSet[m].toString())){
							sparamT.getCvalues().add(sameDsid);
						}else if("ID".equals(mapSet[m].toString())){
							sparamT.getCvalues().add(pkId);
						}else{
							sparamT.getCvalues().add(recordList.get(i).get(mapSet[m])==null?"":recordList.get(i).get(mapSet[m]).toString());
						}

					}
				}
				//判断如果表有ID列，则添加主键,并传入传入32位唯一码
				if(!recordList.get(i).containsKey("ID")){
					recordList.get(i).put("ID","");
					sparamT.getSql().append("ID,");
					sparamT.getTmpSql().append("?,");
					sparamT.getCvalues().add(UUID32.newGuid());
				}
				//如果没有传入主键，则添加关联主键     添加ID  和  DSID 字段
				if(!recordList.get(i).containsKey("DS_ID")){
					recordList.get(i).put("DS_ID", "");
					sparamT.getSql().append("DS_ID,");
					sparamT.getTmpSql().append("?,");
					sparamT.getCvalues().add(sameDsid);
				}
				if(!recordList.get(i).containsKey(pkName)){
					recordList.get(i).put(pkName, "");
					sparamT.getSql().append(pkName+",");
					sparamT.getTmpSql().append("?,");
					sparamT.getCvalues().add(pkStrTmp);
				}

				lastSql.append(sparamT.getSql().substring(0, sparamT.getSql().length()-1)
						+sparamT.getTmpSql().substring(0, sparamT.getTmpSql().length()-1)
						+")");
				//执行sql语句
				System.out.println("CommonSaveDao #L.1975# "+lastSql.toString());
				stmt = conn.prepareStatement(lastSql.toString());
				mapSet = recordList.get(i).keySet().toArray();
				for(int k = 0 ; k < mapSet.length; k ++){
					if("DATE".equals(clnTypeMap.get(mapSet[k]))){
						if("".equals(sparamT.getCvalues().get(k))){
							stmt.setString(k+1, sparamT.getCvalues().get(k));
						}else{
							if(sparamT.getCvalues().get(k)!=null){
								stmt.setTimestamp(k+1, new Timestamp(Long.parseLong(sparamT.getCvalues().get(k))));
							}
						}
					}else{
						stmt.setString(k+1,sparamT.getCvalues().get(k));
					}
					System.out.print(sparamT.getCvalues().get(k).toString()+",");
				}
				stmt.execute();
			}
			conn.commit();
			returnObject.setMsg("success");
			System.out.println("============================pkStrTmp:"+pkStrTmp);
			returnObject.setInfo(pkStrTmp);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e.getMessage()+"[对照表必须有DS_ID和主键列"+pkName+"]");
		}finally{
			if (stmt != null) {
				stmt.close();
			}
			if (conn!= null) {
				conn.close();
			}
		}
		returnObject.setPkValue(sinId);
		return returnObject;
	}



}





